#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif current_os_is_windows; then
   echo "Windows system."
else
   echo "Unknown OS"
fi

APP_INSTALL_NAME="framepack"
APP_TARGET_DIR_NAME="framepack"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda_pytorch.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/env"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:12"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"

if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    export GIT_REPO_URL=${GIT_HOST}/brandon929/FramePack
elif current_os_is_windows; then
    export GIT_REPO_URL=${GIT_HOST}/lllyasviel/FramePack
fi

export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:40"

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

conda --version
echo "lmdprogress:41"
cd "$CURRENT_APP_PATH"
# CONDA_ENV_NAME=$APP_INSTALL_NAME
CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv. remove it. "
    rm -rf "$CONDA_PREFIX"
fi

export PYTHON_VER_ENV="3.10"
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV -y

echo "lmdprogress:45"

cd "$CURRENT_APP_PATH"

echo "lmdprogress:46"
echo "install torch"


function install_ffmpeg {
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_ffmpeg.sh"
}

function check_ffmpeg_and_install_win {
  PROGRAMS=("ffmpeg" "ffprobe")
  missing_programs=0

  for PROGRAM in "${PROGRAMS[@]}"; do
    if ! command -v ${PROGRAM} >/dev/null 2>&1; then
      $PROGRAM -v
      echo "$PROGRAM not found"
      missing_programs=1
    fi
  done

  if [ $missing_programs -eq 1 ]; then
    echo "need install ffmpeg and ffprobe。"
    install_ffmpeg
  else
    echo "ffmpeg and ffprobe exist"
  fi
}

if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    # conda_run_pip_install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
    source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_mac.sh"
    conda_run_conda_forge_install ffmpeg
    echo "lmdprogress:50"
    conda_run_pip_install -r requirements.txt typing_extensions filelock fsspec hf-xet==1.1.7
elif current_os_is_windows; then
    # conda run -p $CONDA_PREFIX --no-capture-output pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
    # source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_win_fixed_ver.sh"
    source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
    check_ffmpeg_and_install_win
    grep -vE '^transformers==' requirements.txt > requirements-temp.txt
    conda_run_pip_install triton-windows transformers==4.53.3
    echo "lmdprogress:50"
    conda_run_pip_install -r requirements-temp.txt typing_extensions filelock fsspec hf-xet==1.1.7
fi

echo "lmdprogress:60"
conda_run_pip_install modelscope

echo "lmdprogress:62"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_flash_attn.sh"

echo "lmdprogress:65"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

echo "start download models"

# Copy download_models.py to app dir. Then run it.
cp "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/download_models.py" "$CURRENT_APP_PATH"

echo "lmdprogress:71"

# echo "global var HF_HOME: "$HF_HOME
export HF_HOME="$CURRENT_APP_PATH/hf_download"
# echo "change HF_HOME:"$HF_HOME

export MODELSCOPE_HOME="$CURRENT_APP_PATH/tmp_modelscope_home"
export MODELSCOPE_CACHE="$CURRENT_APP_PATH/tmp_modelscope_cache"

# conda run -p $CONDA_PREFIX --no-capture-output python -Xfaulthandler "$CURRENT_APP_PATH/download_models.py"

if [ -n "$HF_ENDPOINT" ]; then
    # install with modelscope and save as hf dir
    export HF_HOME="$CURRENT_APP_PATH/tmp_hf_home_by_modelscope"
    export TRANSFORMERS_CACHE="./tmp_hf_home_by_modelscope/hub"
    export TRANSFORMERS_OFFLINE=1
    export HF_HUB_DISABLE_SYMLINKS=1

    echo "lmdprogress:82"
    conda_run_hf_dl_by_modelsople "Xorbits/HunyuanVideo --include text_encoder/" hunyuanvideo-community--HunyuanVideo
    exit_code1=$?

    echo "lmdprogress:84"
    conda_run_hf_dl_by_modelsople "Xorbits/HunyuanVideo --include text_encoder_2/" hunyuanvideo-community--HunyuanVideo
    exit_code2=$?
    
    echo "lmdprogress:86"
    conda_run_hf_dl_by_modelsople "Xorbits/HunyuanVideo --include tokenizer/" hunyuanvideo-community--HunyuanVideo
    exit_code3=$?
    
    echo "lmdprogress:88"
    conda_run_hf_dl_by_modelsople "Xorbits/HunyuanVideo --include tokenizer_2/" hunyuanvideo-community--HunyuanVideo
    exit_code4=$?

    echo "lmdprogress:90"
    conda_run_hf_dl_by_modelsople "Xorbits/HunyuanVideo --include vae/" hunyuanvideo-community--HunyuanVideo
    exit_code5=$?

    echo "lmdprogress:92"
    conda_run_hf_dl_by_modelsople "lllyasviel/flux_redux_bfl --include feature_extractor/" lllyasviel--flux_redux_bfl
    exit_code6=$?

    echo "lmdprogress:94"
    conda_run_hf_dl_by_modelsople "lllyasviel/flux_redux_bfl --include image_encoder/" lllyasviel--flux_redux_bfl
    exit_code7=$?
    
    echo "lmdprogress:96"
    conda_run_hf_dl_by_modelsople "lllyasviel/FramePack_F1_I2V_HY_20250503" lllyasviel--FramePack_F1_I2V_HY_20250503
    exit_code8=$?

    if [ $exit_code1 -eq 0 ] && [ $exit_code2 -eq 0 ] && [ $exit_code3 -eq 0 ] && [ $exit_code4 -eq 0 ] && [ $exit_code8 -eq 0 ]; then
        echo "downloaded all model files."
        if [ -d "$CURRENT_APP_PATH/hf_download" ]; then
            echo "remove hf_download Dir: "$CURRENT_APP_PATH/hf_download
            rm -rf "$CURRENT_APP_PATH/hf_download"
        fi
    fi

else
    echo "lmdprogress:82"
    conda_run_hf_download facebook/w2v-bert-2.0
    echo "lmdprogress:84"
    conda_run_hf_download amphion/MaskGCT semantic_codec/model.safetensors
    echo "lmdprogress:86"
    conda_run_hf_download funasr/campplus campplus_cn_common.bin
    echo "lmdprogress:90"
    conda_run_hf_download nvidia/bigvgan_v2_22khz_80band_256x config.json bigvgan_generator.pt
fi

echo "lmdprogress:100"


